package service

import (
	"errors"
	"fmt"
	"go_my_framework/app/dao"
	"go_my_framework/app/global/e"
	"go_my_framework/app/global/request"
	"go_my_framework/app/model"
	"go_my_framework/util/sli"
	"html/template"
	"strings"
)

type PurviewService struct {
}

type PurviewTree struct {
	Id     int
	Pid    int
	Level  int
	SubLen int
	Name   string
	Url    string
	Repeat string
	Sub    []PurviewTree
}

type FormatTree struct {
	Id      int    `json:"id"`
	PId     int    `json:"pId"`
	Name    string `json:"name"`
	Checked bool   `json:"checked"`
}

// 获取管理员列表
func (p *PurviewService) GetPurviewList(f request.PurviewForm) ([]model.Purview, int64, error) {
	if f.Page == 0 {
		f.Page = 1
	}
	if f.Limit == 0 {
		f.Limit = 10
	}
	data, count, err := dao.NewPurviewDaoImpl().GetList(f.Page, f.Limit, f.Name)
	if err != nil {
		return []model.Purview{}, 0, errors.New(err.Error())
	}

	return data, count, nil
}

func (p *PurviewService) GetRow(id int) (model.Purview, error) {
	purview, err := dao.NewPurviewDaoImpl().FindRow(id)
	if err != nil {
		return model.Purview{}, errors.New(err.Error())
	}
	return purview, nil
}

func (p *PurviewService) GetRowByUrl(url string) (model.Purview, error) {
	purview, err := dao.NewPurviewDaoImpl().FindRowByUrl(url)
	if err != nil {
		return model.Purview{}, errors.New(err.Error())
	}
	return purview, nil
}

func (p *PurviewService) AddPurview(name string, pid int, url string, isShow int8, sort int, icon string) error {
	return dao.NewPurviewDaoImpl().Create(name, pid, url, isShow, sort, icon)
}

func (p *PurviewService) EditPurview(id int, name string, pid int, url string, isShow int8, sort int, icon string) error {
	return dao.NewPurviewDaoImpl().Update(id, name, pid, url, isShow, sort, icon)
}

func (p *PurviewService) GetPurviewTree(Pid int) string {
	list, _, _ := dao.NewPurviewDaoImpl().GetList(1, 10000, "")
	listTree := Tree(list, 0, 0)
	treeHtml := TreeHtml(listTree, Pid)

	return treeHtml
}

func (p *PurviewService) GetAll(selectSli []int) []FormatTree {
	data, _, _ := dao.NewPurviewDaoImpl().GetList(1, 10000, "")
	list := formatTreeData(data, selectSli)
	return list
}

func (p *PurviewService) DelRow(id int) error {
	return dao.NewPurviewDaoImpl().Del(id)
}

func (p *PurviewService) GetMenusTree(roleId int, allowIds []int) string {
	list, _, _ := dao.NewPurviewDaoImpl().GetList(1, 10000, "")
	listTree := Tree(list, 0, 0)

	// 角色拥有的权限
	allowList := p.GetPurviewByIds(allowIds)
	urls := make([]int, len(allowList), len(allowList))
	for k, v := range allowList {
		urls[k] = v.Id
	}
	return MenusTreeHtml(listTree, roleId, urls)
}

func (p *PurviewService) GetPurviewByIds(ids []int) []model.Purview {
	purviewList, _ := dao.NewPurviewDaoImpl().GetListByIds(ids, []string{"*"})
	return purviewList
}


func Tree(list []model.Purview, pid int, level int) []PurviewTree {
	var returnList []PurviewTree
	for _, v := range list {
		if v.Pid == pid {
			var tmp PurviewTree
			tmp.Id = v.Id
			tmp.Name = v.Name
			tmp.Pid = v.Pid
			tmp.Url = v.Url
			tmp.Level = level
			tmp.Repeat = strings.Repeat(string(template.HTML("&nbsp;&nbsp;")), level) + "├─"
			tmp.Sub = Tree(list, tmp.Id, level+1)
			tmp.SubLen = len(tmp.Sub)
			returnList = append(returnList, tmp)
		}
	}
	return returnList
}

func TreeHtml(listTree []PurviewTree, Pid int) string {
	treeHtml := ""
	for _, v := range listTree {
		selectStr := ""
		if Pid != 0 && Pid == v.Id {
			selectStr = "selected"
		} else {
			selectStr = ""
		}
		treeHtml += fmt.Sprintf("<option value='%d' %s>%s %s </option>", v.Id, selectStr, v.Repeat, v.Name)
		if v.SubLen > 0 {
			treeHtml += TreeHtml(v.Sub, Pid)
		}
	}
	return treeHtml
}

func formatTreeData(list []model.Purview, selectSli []int) []FormatTree {
	if len(list) == 0 {
		return []FormatTree{}
	}
	var returnList []FormatTree
	for _, v := range list {
		var tmp FormatTree
		tmp.Id = v.Id
		tmp.PId = v.Pid
		tmp.Name = v.Name
		if len(selectSli) > 0 && sli.InArray(tmp.Id, selectSli) {
			tmp.Checked = true
		} else {
			tmp.Checked = false
		}
		returnList = append(returnList, tmp)
	}
	return returnList
}

func MenusTreeHtml(listTree []PurviewTree, roleId int, allowIds []int) string {
	treeHtml := ""
	for _, v := range listTree {
		// 不属于该玩家的权限不展示
		if roleId != e.SuperRoleId && !sli.InArray(v.Id, allowIds) {
			continue
		}
		treeHtml += "" +
			"<li>" +
			"<a href=\"javascript:;\">" +
			"<i class=\"iconfont left-nav-li\" lay-tips=\"{$arrVal.name}\">&#xe723;</i>" +
			"<cite>" + v.Name + "</cite>" +
			"<i class=\"iconfont nav_right\">&#xe697;</i>" +
			"</a>" +
			"<ul class=\"sub-menu\">"
		if v.SubLen > 0 {
			for _, vv := range v.Sub {
				// 不属于该玩家的权限不展示
				if roleId != e.SuperRoleId && !sli.InArray(vv.Id, allowIds) {
					continue
				}
				treeHtml += "" +
					"<li>" +
						"<a onclick=\"xadmin.add_tab('" + vv.Name + "','" + vv.Url + "')\">" +
							"<i class=\"iconfont\">&#xe6a7;</i>" +
							"<cite>" + vv.Name + "</cite>" +
						"</a>" +
					"</li>"
			}
		}
		treeHtml += "</ul></li>"
	}
	return treeHtml
}